package com.example.exchangeapp.pxx;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.exchangeapp.R;
import com.example.exchangeapp.pxx.Record;

import java.util.List;

public class RecordsAdapter extends ArrayAdapter<Record> {
    private List<Record> records;
    private Context context;
    private int resourceId;

    public RecordsAdapter(Context context, int resourceId, List<Record> records) {
        super(context, resourceId, records);
        this.context = context;
        this.records = records;
        this.resourceId = resourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Record record = getItem(position);
        View view ;

        final ViewHolder vh;

        if (convertView == null) {
            view = LayoutInflater.from(getContext())
                    .inflate(resourceId, parent, false);

            vh = new ViewHolder();
            vh.goodImage  = view.findViewById(R.id.good_image);
            vh.goodDes = view.findViewById(R.id.good_des);
            vh.goodPrice = view.findViewById(R.id.good_price);
            vh.createTime = view.findViewById(R.id.create_time);
            vh.sellername = view.findViewById(R.id.sellername);

            view.setTag(vh);
        } else {
            view = convertView;
            vh = (ViewHolder) view.getTag();
        }

        if(record.getGoodsDescription()!=null){
            String desc=record.getGoodsDescription();
            if (record.getGoodsDescription().length()>10){
                desc=record.getGoodsDescription().toString().substring(0,10);
                desc=desc+"...";
            }
            vh.goodDes.setText("商品详情:"+desc);
        }
        if(record.getPrice()!=null){
            vh.goodPrice.setText("商品价格:"+record.getPrice()+"元");
        }
        if(record.getCreateTime()!=null){
            vh.createTime.setText("交易时间:"+record.getCreateTime());
        }
        if(record.getSellerName()!=null){
            vh.sellername.setText("交易用户名:"+record.getSellerName());
        }
        if(record.getImageUrlList()!=null){
            if(record.getImageUrlList().size()>0){
                Glide.with(context).load(record.getImageUrlList().get(0))
                        .into(vh.goodImage);
            }
        }
        return view;
    }

    class ViewHolder {
        ImageView goodImage;
        TextView goodDes;
        TextView goodPrice;
        TextView createTime;
        TextView sellername;
    }
}
